let express = require('express');
let router = express.Router();

const bookService = require('../service/bookService');

// 引入jwt验证方法的中间件
const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');
router.use(checkJWTMiddleWare);

/*
 * 懒加载获取参考书籍接口
 */
router.post('/getRecommendBook', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { lastId } = req.body;
    let result = await bookService.getCommendBook(uid, lastId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 加入书架接口
 */
router.post('/joinInLib', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { bookId } = req.body;
    let result = await bookService.joinInLib(uid, bookId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 取消加入书架接口
 */
router.post('/noJoinInLib', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { bookId } = req.body;
    let result = await bookService.noJoinInLib(uid, bookId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 懒加载获取书架中所有书籍接口
 */
router.post('/getJoinBook', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { lastId } = req.body;
    let result = await bookService.getJoinBook(uid, lastId);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 获取书本内容接口
 */
router.post('/getBookContent', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { bookId } = req.body;
    let result = await bookService.getBookContent(bookId, uid);
    res.status(result.success ? 200 : 400).json(result);
});

/*
 * 获取所有书本接口
 */
router.get('/getAllBook', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let page = parseInt(req.query.page || 1);
    let result = await bookService.getAllBook(uid, page);
    res.status(result.success ? 200 : 400).json(result);
});

// 搜索书本的接口
router.post('/searchBook', async function(req, res, next) {
    let uid = req.jwtResult.data.uid;
    let { bookName } = req.body;
    if (!bookName) {
        return res.status(400).json({
            success: false,
            message: '搜索内容不能为空'
        });
    }
    let result = await bookService.searchBook(uid, bookName);
    res.status(result.success ? 200 : 400).json(result);
});

module.exports = router;